package net.loststone;

import net.loststone.*;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

class AbstractEconInfoService {
    public static String GASTO_MEDIO_DEBIDO_VIVIENDA = "Gasto Medio debido a la Vivienda";
    public static String GASTO_MEDIO_POR_HOGAR = "Gasto medio por hogar (persona)";
    public static String RENTA_FAMILIAR_DISPONIBLE_BRUTA = "Renta familiar disponible bruta"

    /**
     * Mira si el EconInfo que rep com a parametre ja existeix, en cas de que si
     * l'actualitza, si no el crea
     */
    def updateOrSave(EconInfo nou) {
        // mirem si ja esta a la db.
        def dupId = EconInfo.isDuplicated(nou)
        if (dupId == -1) {
            nou.save();
            log.info("Insertant ${nou.nom} a ${nou.afecta?.name} amb valor: ${nou.valor}")
        } else {
            def update = EconInfo.get(dupId)
            update.valor = nou.valor
            update.save()
            log.info("Actualitzant ${update.nom} a ${update.afecta?.name} al valor: ${nou.valor}")
        }
    }

  def getCSV(url) {

    HttpClient httpClient;
    HttpMethod method;
    httpClient = new HttpClient();
    method = new GetMethod(url);

    int statusCode = httpClient.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
      throw new Exception("No s'ha pogut recuperar el fitxer de l'INE.");
    }

    return method.getResponseBody();

  }

   /**
   * Agafa l'excel dels internets
   */
  def getExcel(url) {

    HttpClient httpClient;
    HttpMethod method;
    httpClient = new HttpClient();
    method = new GetMethod(url);

    int statusCode = httpClient.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
      throw new Exception("No s'ha pogut recuperar excel de "+url);
    }

    return method.getResponseBodyAsStream();

  }
}
